import React, { useState, useEffect, forwardRef, useImperativeHandle, useCallback } from 'react';
import { useDispatch } from 'umi';
import {
  message,
  Button,
  Popconfirm,
  Divider,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import EditableTable from '../EditableTable';
import PaginationCommon from '../PaginationCommon';
import styles from './PositionManageTable.less';

let newPrimaryId = 0;
const PositionManage = (props, ref) => {
  const { orgId, handleSuccess, showOperateColumn = true, showAddOperate = true, setSubLoading = () => { } } = props;
  const [currenPageNum, setCurrenPageNum] = useState(1);
  const [currenPageSize, setCurrenPageSize] = useState(5);
  const [dataSource, setDataSource] = useState([]);
  const [totalCount, setTotalCount] = useState([]);
  const [delList, setDelList] = useState([]);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  const createRequestPromise = useCallback((dispatchParam, errMsg) =>
    new Promise((resolve, reject) => {
      dispatch(dispatchParam).then((res) => {
        const { code, message } = res;
        if (code !== 0) {
          reject(message || errMsg);
        } else {
          resolve();
        }
      });
    }), [dispatch]);

  useEffect(() => {
    if (orgId) {
      setLoading(true);
      dispatch({
        type: 'orgManageModel/getPositionList',
        payload: {
          orgId,
          pageIndex: currenPageNum,
          pageSize: currenPageSize,
        },
      }).then((data) => {
        const { dataList, total } = data;
        setDataSource(
          delList.length > 0
            ? dataList.map(item => ({
              ...item,
              ...(delList.includes(item.id) && { isDel: true }),
            }))
            : dataList,
        );
        setTotalCount(total);
        setLoading(false);
      });
    }
    return () => {
      newPrimaryId = 0;
    };
  }, [orgId, currenPageNum, currenPageSize, dispatch, delList]);

  const handleDelete = (record) => {
    const { key, id } = record;
    if (id) {
      setDelList([...delList, id]);
      setDataSource(
        [...dataSource].map(item => ({ ...item, ...(item.id === id && { isDel: true }) })),
      );
    } else {
      setDataSource([...dataSource].filter(item => item.key !== key));
    }
  };

  const handleCancelDelete = (record) => {
    const { id } = record;
    if (id) {
      const newDelList = [...delList];
      const delIndex = newDelList.indexOf(id);
      if (delIndex > -1) newDelList.splice(delIndex, 1);
      setDelList(newDelList);
      setDataSource(
        [...dataSource].map(item => ({ ...item, ...(item.id === id && { isDel: false }) })),
      );
    }
  };

  const handleSetPrimary = (record) => {
    const { key, id } = record;
    setDataSource(
      [...dataSource].map(item => ({
        ...item,
        ...{ isPrimary: (id && item.id === id) || (key && item.key === key) ? 1 : 0 },
      })),
    );
    newPrimaryId = record.id;
  };

  const handleDataSourceChange = (data) => {
    setDataSource(data);
  };

  const handleAddRow = (flag = 'new') => {
    const newRowListLength = dataSource.filter(item => !item.id).length;
    if (newRowListLength === 5) {
      message.warn('单次最多新增五条数据');
      return false;
    }
    const newData = {
      key: `${flag}-${newRowListLength}`,
      name: undefined,
      isPrimary: 0,
    };
    handleDataSourceChange([newData, ...dataSource]);
    return null;
  };

  const handleSubmit = ({ orgId: orgIdParam, callback: successCallback }) => {
    let p1 = null;
    let p2 = null;
    let p3 = null;
    const addList = dataSource.filter(item => !item.id);
    // 校验
    if (addList.some(d => !d.name)) return;
    setSubLoading(true);
    if (addList.length > 0) {
      p1 = createRequestPromise(
        {
          type: 'orgManageModel/addPosition',
          payload: addList.map(({ name, isPrimary }) => ({
            orgId: orgId || orgIdParam,
            name,
            isPrimary,
          })),
        },
        '岗位添加失败',
      );
    }
    if (delList.length > 0) {
      p2 = createRequestPromise(
        { type: 'orgManageModel/delPosition', payload: delList },
        '岗位删除失败',
      );
    }
    if (newPrimaryId) {
      p3 = createRequestPromise(
        { type: 'orgManageModel/setMainPosition', payload: { id: newPrimaryId }},
        '设为主岗失败',
      );
    }
    Promise.all([p1, p3, p2])
      .then((result) => {
        if (handleSuccess) {
          handleSuccess();
        } else if (successCallback) {
          successCallback();
        }
        setSubLoading(false);
      })
      .catch((error) => {
        message.error(error);
        setSubLoading(false);
      });
  };

  useImperativeHandle(ref, () => ({
    handleSubmit,
  }));

  const handlePaginationChange = (page, pageSize) => {
    setCurrenPageNum(page);
    setCurrenPageSize(pageSize);
  };

  const columns = [
    {
      title: '岗位名称',
      key: 'name',
      dataIndex: 'name',
      width: '30%',
      editable: true,
    },
    {
      title: '标识',
      key: 'isPrimary',
      dataIndex: 'isPrimary',
      width: '30%',
      render: text => (text === 1 ? '主岗' : '非主岗'),
    },
  ];

  if (showOperateColumn) {
    columns.push({
      title: '操作',
      dataIndex: 'operation',
      width: '30%',
      render: (_, record) => (
        <div>
          {!record.isDel && record.name && !record.isPrimary && (
            <>
              <Popconfirm
                title="确定设置该岗位为主岗吗?"
                onConfirm={() => handleSetPrimary(record)}
              >
                <a>设为主岗</a>
              </Popconfirm>
              <Divider type="vertical" />
            </>
          )}
          {record.isDel ? (
            <Button type="link" onClick={() => handleCancelDelete(record)}>
              取消删除
            </Button>
          ) : (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
        </div>
      ),
    });
  }

  return (
    <div>
      <div className={styles.editableTableTitle}>
        <div className={styles.title}>岗位信息</div>
        {showAddOperate && (
          <div>
            <Button type="link" onClick={() => handleAddRow('exist')} style={{ padding: 4 }}>
              <PlusOutlined />
              添加已有岗位
            </Button>
            <Button type="link" onClick={() => handleAddRow('new')} style={{ padding: 4 }}>
              <PlusOutlined />
              自定义添加
            </Button>
          </div>
        )}
      </div>
      <EditableTable
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        handleDataSourceChange={handleDataSourceChange}
        pagination={false}
      />
      <PaginationCommon
        total={totalCount}
        onChange={handlePaginationChange}
        style={{ textAlign: 'right' }}
        current={currenPageNum}
        pageSize={currenPageSize}
      />
    </div>
  );
};

export default forwardRef(PositionManage);
